package com.qhit.controller;

import com.qhit.pojo.Permission;
import com.qhit.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model,@RequestParam String keywords,
                       @RequestParam(defaultValue = "1") Integer pageSize,
                       @RequestParam(defaultValue = "0") Integer page,
                       @RequestParam(defaultValue = "1") Integer pageNo){

        HashMap hashMap = new HashMap<>();
        hashMap.put("keywords",keywords);
        hashMap.put("pageSize",pageSize);
        hashMap.put("page",page);
        hashMap.put("pageNo",pageNo);
        long total=permissionService.getListCount(hashMap);
        System.out.println(total);
        hashMap.put("totalPage",(total%pageSize==0?(total/pageSize):((total/pageSize)+1)));
        List<Permission> list =  permissionService.getList(hashMap);
        model.addAttribute("list",list);
        model.addAttribute("myParams",hashMap);
        return "permission/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd (){
        return "permission/add";
    }
    @PostMapping("/add")
    public String add ( Permission permission , Model model){
        int i = permissionService.add(permission);
        if(i>0){
            model.addAttribute("msg","添加成功");
        }else {
            model.addAttribute("msg","添加失败");
        }
        return "permission/msg";
    }
    @RequestMapping("/toEdit/{id}")
    public String toEdit (@PathVariable("id") Integer id,Model model){
        Permission permission=permissionService.getPermissionById(id);
        model.addAttribute("permission",permission);
        return "permission/edit";
    }
    @RequestMapping("/delete/{id}")
    public String delete (@PathVariable("id") Integer id,Model model){
        int i=permissionService.delete(id);
        if(i>0){
            model.addAttribute("msg","删除成功");
        }else {
            model.addAttribute("msg","删除成功");
        }
        return "permission/msg";
    }
    @PostMapping("/edit")
    public String edit ( Permission permission , Model model){
        System.out.println(permission);
        int i = permissionService.edit(permission);

        if(i>0){
            model.addAttribute("msg","修改成功");
        }else {
            model.addAttribute("msg","修改失败");
        }
        return "permission/msg";
    }
}
